import {
  reqGetCartList,
  reqAddToCart,
  reqUpdateCartIsChecked,
  reqDelCart,
  reqBatchDelCart,
  reqBatchCheckCart,
} from "@/api/shopcart";

export default {
  state: {
    cartList: [],
  },
  getters: {},
  actions: {
    // 获取cartList
    async getCartList({ commit }) {
      const res = await reqGetCartList();
      if (res[0]) {
        commit("GET_CART_LIST", res[0].cartInfoList);
      } else {
        commit("GET_CART_LIST", []);
      }
    },
    // 更新商品数量
    async updateCartSkuNum({ commit }, { skuId, newSkuNum, oldSkuNum }) {
      const skuNum = newSkuNum - oldSkuNum;
      // 发送请求，更新服务器数据
      await reqAddToCart(skuId, skuNum);
      // 更新客户端数据
      commit("UPDATE_CART_SKU_NUM", { skuId, newSkuNum });
    },
    // 更新商品选中状态
    async updateCartIsChecked({ commit }, { skuId, isChecked }) {
      await reqUpdateCartIsChecked(skuId, isChecked);
      commit("UPDATE_CART_IS_CHECKED", { skuId, isChecked });
    },
    // 批量选中
    async batchCheckCart({ commit, state }, isChecked) {
      const skuIdList = state.cartList.reduce((p, c) => {
        // 不相等不改
        if (c.isChecked !== isChecked) {
          return [...p, c.skuId];
        } else {
          return p;
        }
      }, []);
      await reqBatchCheckCart(skuIdList, isChecked);
      commit("BATCH_CHECK_CART", isChecked);
    },
    // 单个删除
    async delCart({ commit }, skuId) {
      await reqDelCart(skuId);
      commit("DEL_CART", skuId);
    },
    // 批量删除
    async batchDelCart({ commit, state }) {
      const skuIdList = state.cartList.reduce((p, c) => {
        if (c.isChecked) {
          return [...p, c.skuId];
          // p.push(c.skuId);
          // return p;
        } else {
          return p;
        }
      }, []);
      await reqBatchDelCart(skuIdList);
      commit("BATCH_DEL_CART");
    },
  },
  mutations: {
    GET_CART_LIST(state, cartList) {
      state.cartList = cartList;
    },
    UPDATE_CART_SKU_NUM(state, { skuId, newSkuNum }) {
      // 查找对应的数据
      const cart = state.cartList.find((cart) => cart.skuId === skuId);
      // 修改
      cart.skuNum = newSkuNum;
    },
    UPDATE_CART_IS_CHECKED(state, { skuId, isChecked }) {
      const cart = state.cartList.find((cart) => cart.skuId === skuId);
      cart.isChecked = isChecked;
    },
    DEL_CART(state, skuId) {
      state.cartList = state.cartList.filter((cart) => cart.skuId !== skuId);
    },
    BATCH_DEL_CART(state) {
      state.cartList = state.cartList.filter((cart) => !cart.isChecked);
    },
    BATCH_CHECK_CART(state, isChecked) {
      state.cartList.forEach((cart) => (cart.isChecked = isChecked));
    },
  },
  namespaced: true,
};
